<?php

/**
 * Emms api functions
 *
 * @author Andrés B
 */
class Emms_Api
{
    
    private $_validUser = false;
    
    private static $_rowCount = 10;
    private static $_rowCountMax = 100;
    private static $_rowOffset = 0;
    private static $_rowOrder = 'ASC';
    
    private static $_tables = array
    (
       'Clients' => array('name' => 'view_clients', 'primary' => 'ClientId'),
       'Loans'   => array('name' => 'view_loans', 'primary' => 'LoanId'),
       'Funds'   => array
        (
           'name' => 'view_funds', 
           'primary' => 'FundId', 
           'post' => array
            (
               'name' => 'funds',
               'form' => 'Emms_Form_Admin_Fund',
               'fields' => array('Fund','Code','Comments')
            )
        )
    );
    
    private function _getModel($tbl, $post = null)
    {
        if(isset(self::$_tables[$tbl]))
            return new Zend_Db_Table(array(
                'name' => $post ? self::$_tables[$tbl]['post']['name'] : self::$_tables[$tbl]['name'], 
                'primary' => self::$_tables[$tbl]['primary']));
        throw new SoapFault("Server", "Invalid request");
    }
    
    public function auth($cl,$db,$usr,$pwd,$loc) 
    {
        $credTreatment = sprintf('md5(?) and Status = "Active" 
                    and SystemAccessFromDate <= "%s" 
                    and SystemAccessToDate >= "%s"', date("Y-m-d"), date("Y-m-d"));
        $login = new HTech_Login($cl,$db,$usr,$pwd,'view_users','Username','Password',$credTreatment);
        if (!$login->authenticate()->isValid())
            throw new SoapFault("Server", sprintf("Invalid login info: %s:%s@%s_%s",$usr,$pwd,$cl,$db));
        
        $this->_validUser = true;
        $config = new Zend_Config_Ini(APPLICATION_PATH . '/configs/config.ini', $cl . '_' . $db);
        Zend_Registry::set('HT_Config', $config);
        Zend_Registry::set('Zend_Locale', $loc);
        HTech_Locale::setLocaleObj($loc);
        HTech_Locale::setTranslateObj();
        $login->saveProfile();
    }
    
    /**
     * This method1 takes ...
     *
     * @param string $inputParam
     * @return array
     */
    public function method1($inputParam) 
    {
        $result = new stdClass();
        $result->par1 = $inputParam;
        $result->par2 = $_SERVER['HTTP_HOST'];
        $result->par3 = $_SERVER['REQUEST_URI'];
        return (array)$_SERVER;
    }
    
    /**
     * This post takes ...
     *
     * @param string $tbl
     * @param array $data
     * @return object
     */
    public function post($tbl,$data) 
    {
        $model = $this->_getModel($tbl);
        $primary = current($model->info('primary'));
        $id = $data[$primary];
        Zend_Controller_Front::getInstance()->getRequest()->setPost($primary, $id);
        $form = new self::$_tables[$tbl]['post']['form']();
        foreach(self::$_tables[$tbl]['post']['fields'] as $field) {
            if(isset($data[$field])) {
                if(!$form->getElement($field)->isValid($data[$field])) {
                    throw new SoapFault("Server", sprintf("Invalid %s (%s)", 
                        $field, current($form->getElement($field)->getMessages()))); 
                } else {
                    $d[$field] = $data[$field];
                }
            }
        }
        try {
            $model->update($d + $form->getXtraValues(),sprintf('%s = %s', $primary, $id));
        } catch (Exception $e) {
            throw new SoapFault("Server", $e->getMessage());
        }
        return $this->byId($tbl,$id);
    }
 
    /**
     * This byId takes ...
     *
     * @param string $table
     * @param int $id
     * @return object
     */
    public function byId($tbl,$id) 
    {
        return json_encode($this->_getModel($tbl)->find((int) $id)->toArray());
    }
 
    /**
     * This count takes ...
     *
     * @param string $table
     * @param int $id
     * @return object
     */
    public function count($tbl,$id) 
    {
        $model = $this->_getModel($tbl);
        $select = $model->select()
            ->from($model,array('count(*) as count'))
            ->where(current($model->info('primary')) . ' > ' . (int) $id);
        return json_encode($model->fetchAll($select)->toArray());
    }
 
    /**
     * This get takes ...
     *
     * @param string $table
     * @param int $count
     * @param int $offset
     * @param string $order
     * @return object
     */
    public function get($tbl,$count,$offset,$order) 
    {
        $count = (int) $count ? min((int) $count, self::$_rowCountMax) : self::$_rowCount;
        $offset = (int) $offset ? (int) $offset : self::$_rowOffset;
        $order = (($order == 'ASC')||($order == 'DESC')) ? $order : self::$_rowOrder;   
        $model = $this->_getModel($tbl);
        $select = $model->select()
            ->order(current($model->info('primary')) . ' ' . $order)
            ->limit($count, $offset);
        return json_encode($model->fetchAll($select)->toArray());
    }
}
